/**
 * Copyright millionhere
 * Licensed under the Apache License, Version 2.0 (the "License");
 * You may see it at...
 *      http://www.apache.org/licenses/LICENSE-2.0
 */

package info.millionhere.keepsilent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.StringWriter;

import org.xmlpull.v1.XmlSerializer;

import android.os.Environment;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.util.Log;
import android.util.Xml;

public class ConfigXmlAdaptor {
    static final String TAG_ROOT = "config";
    static final String TAG_SERVICEONBOOT = "onboot";
    
    
    private static final String CONFIG_PATH = "/KeepSilent/";
    private static final String CONFIG_NAME = "/config.xml";
    
    private boolean serviceOnBoot;
    
    public ConfigXmlAdaptor(){
	if (read()){
	}
	else{
	    serviceOnBoot = false;
	}
    }
    
    private boolean read(){
	
	RootElement root = new RootElement("", TAG_ROOT);

	//Handle TAG_SERVICEONBOOT
	root.getChild("", TAG_SERVICEONBOOT).setEndTextElementListener(new EndTextElementListener() {
	    public void end(String currentData) {
		serviceOnBoot = (currentData.equalsIgnoreCase("true"))?true:false;
	    }
	});

	try{
	    FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory() + CONFIG_PATH + CONFIG_NAME);
	    Xml.parse(fis, Xml.Encoding.UTF_8, root.getContentHandler());
	} catch (Exception e) {
	    Log.e("READ", "Read Config XML Failed");
	    return false;
	}
	
	return true;
    }
    
    private String write(){
	XmlSerializer serializer = Xml.newSerializer();
	StringWriter writer = new StringWriter();
	
	try{
	    serializer.setOutput(writer);

	    serializer.startDocument("UTF-8", true);

	    serializer.startTag("", TAG_ROOT);

	  //Handle TAG_SERVICEONBOOT
	    serializer.startTag("", TAG_SERVICEONBOOT);
	    serializer.text(serviceOnBoot?"true":"false");
	    serializer.endTag("", TAG_SERVICEONBOOT);
	    
	    serializer.endTag("", TAG_ROOT);

	    serializer.endDocument();
	    
	    confirmAppFolder();
	    
	    FileWriter fw = new FileWriter(Environment.getExternalStorageDirectory() + CONFIG_PATH + CONFIG_NAME);
	    fw.write(writer.toString());
	    fw.close();
	}
	catch(Exception e)
	{
	    return e.getMessage();
	}
	return writer.toString();
    }
    
    private int confirmAppFolder(){
	File path = new File(Environment.getExternalStorageDirectory() + CONFIG_PATH);
	if (!path.exists())
	    path.mkdirs();
	return 0;
    }
    
    public boolean GetServiceOnBoot(){
	return this.serviceOnBoot;
    }
    
    public String SetServiceOnBoot(boolean serviceOnBoot){
	this.serviceOnBoot = serviceOnBoot;
	
	return write();
    }
}
